package com.rocsun.web.config;

import com.rocsun.web.interceptor.AuthHandlerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @program: rocsun-scali
 * @description:
 * @author: yx.guo
 * @create: 2025-10-20 23:13
 **/
// 方式1：全局配置（推荐）
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private AuthHandlerInterceptor authHandlerInterceptor;

    /**
     * 操作跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 允许所有接口
        registry.addMapping("/**")
                // 允许前端的源
                .allowedOrigins("http://localhost:5173")
                // 允许的请求方法
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                // 默认只会暴露简单头 （Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma）
                // 对于非简单头，或者自定义头，必须在此处列出，前端才能访问
                .exposedHeaders("Authorization")
                // 允许携带Cookie
                .allowCredentials(true)
                // 预检请求的有效期（秒）
                .maxAge(3600);
    }

    /**
     * 添加拦截器
     * 给除了 /login 之外所有接口添加拦截器，拦截转向到 authHandlerInterceptor
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authHandlerInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/api/auth/login",
                        "/api/auth/login/**",
                        "/api/auth/register",   // 注册接口
                        "/error",              // 错误端点
                        "/swagger-ui/**",
                        "/v3/api-docs/**",
                        "/webjars/**",
                        "/doc.html"
                );
    }
}
